<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入合同号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报价单号" prop="offerCode">
        <el-input
          v-model="queryParams.offerCode"
          placeholder="请输入报价单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="询价单号" prop="inquireCode">
        <el-input
          v-model="queryParams.inquireCode"
          placeholder="请输入询价单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物流方式" prop="logisticsModule">
        <el-select v-model="queryParams.logisticsModule" placeholder="请选择物流方式" clearable>
          <el-option
            v-for="dict in dict.type.wms_logistics"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否物流" prop="ifLogistics">
        <el-select v-model="queryParams.ifLogistics" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付类型" prop="payType">
        <el-select v-model="queryParams.payType" placeholder="请选择支付类型" clearable>
          <el-option
            v-for="dict in dict.type.wms_pay_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.wms_contract_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          size="mini"
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handlePurchase"
          :disabled="multiple"
          v-hasPermi="['wms:contractOrder:purchase']"
        >采购</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractOrderList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="50" :selectable="handelTableIsSelect"/>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="支付类型">
              <dict-tag :options="dict.type.wms_pay_type" :value="props.row.payType"/>
            </el-form-item>
            <el-row :gutter="10" v-if="props.row.ifLogistics === 'Y'">
              <el-col :span="12">
                <el-form-item label="物流方式">
                  <dict-tag :options="dict.type.wms_logistics" :value="props.row.logisticsModule"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物流条款">
                  <span>{{ props.row.logisticsTerms }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-if="props.row.payType === '1'">
              <el-col :span="12">
                <el-form-item label="先款比例">
                  <span>{{ props.row.prefixPayRate }}</span>
                  <span style="margin-left: 10px">备注：{{props.row.prefixRemark}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="进度款比例">
                  <span>{{ props.row.processPayRate }}</span>
                  <span style="margin-left: 10px">备注：{{props.row.processRemark}}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-if="props.row.payType === '1'">
              <el-col :span="12">
                <el-form-item label="尾款比例">
                  <span>{{ props.row.tailPayRate }}</span>
                  <span style="margin-left: 10px">备注：{{props.row.tailRemark}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="尾款支付时间">
                  <span>货到后{{ props.row.tailPayTime }}天付款</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="合同金额">
                  <span>{{ props.row.contractPrice }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="已支付金额">
                  <span>{{ props.row.payPrice }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="合同号" align="center" prop="orderCode" >
        <template slot-scope="scope">
          <el-link type="primary" @click="handleLook(scope.row)">{{ scope.row.orderCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="报价单号" align="center" prop="offerCode" />
      <el-table-column label="询价单号" align="center" prop="inquireCode" />
      <el-table-column label="是否物流" align="center" prop="ifLogistics" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.ifLogistics"/>
        </template>
      </el-table-column>
      <el-table-column label="采购百分比" align="center" prop="cgRate" />
      <el-table-column label="物流百分比" align="center" prop="wlRate" />
      <el-table-column label="完成百分比" align="center" prop="rate" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_contract_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 采购对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="formContract" :model="formContract" :rules="rulesContract" label-width="130px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="合同号" >
              {{formContract.offerCode}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内容数量" >
              {{formContract.productNum}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="采购金额" >
              {{formContract.purchasePrice}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购金额(含税)" >
              {{formContract.purchasePrice}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="支付类型" prop="payType">
              <el-radio-group v-model="formContract.payType" @change="handlePayTypeChange">
                <el-radio
                  v-for="dict in dict.type.wms_pay_type"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="先款比例" prop="prefixPayRate" v-if="formContract.payType === '1'">
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-input v-model="formContract.prefixPayRate" placeholder="请输入先款比例" />
                </el-col>
                <el-col :span="12">
                  <el-input v-model="formContract.prefixRemark" :maxlength="255" placeholder="请输入先款备注">
                    <template slot="prepend">备注</template>
                  </el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" v-if="formContract.payType === '1'">
          <el-col :span="12">
            <el-form-item label="进度款比例" prop="processPayRate">
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-input v-model="formContract.processPayRate" placeholder="请输入进度款比例" />
                </el-col>
                <el-col :span="12">
                  <el-input v-model="formContract.processRemark" :maxlength="255" placeholder="请输入进度款备注">
                    <template slot="prepend">备注</template>
                  </el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="尾款比例" prop="tailPayRate">
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-input v-model="formContract.tailPayRate" placeholder="请输入尾款比例" />
                </el-col>
                <el-col :span="12">
                  <el-input v-model="formContract.tailRemark" :maxlength="255" placeholder="请输入尾款备注">
                    <template slot="prepend">备注</template>
                  </el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="支付金额" prop="payPrice">
              <el-input v-model="formContract.payPrice" placeholder="请输入支付金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formContract.payType === '1'">
            <el-form-item prop="tailPayTime">
              <template slot="label">
                尾款支付时间
                <el-tooltip class="item" effect="dark" content="货到后几天付款，0代表货到立即付款" placement="bottom">
                  <i class="el-icon-warning-outline"></i>
                </el-tooltip>
              </template>
              <el-input v-model="formContract.tailPayTime" placeholder="请输入货到几天后付款" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="合同附件">
          <el-upload
            class="upload-demo"
            :headers="uploadAccessory.headers"
            :action="uploadAccessory.url"
            :on-remove="handleRemove"
            :on-success="handlePiceSuccess"
            multiple
            drag
            accept=".jpg,.png,.jpeg,.xlsx,.xls"
            :file-list="fileList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入jpg/png/pdf格式文件。</span>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="支付附件">
          <el-upload
            class="upload-demo"
            :headers="uploadAccessory.headers"
            :action="uploadAccessory.url"
            :on-remove="handlePayRemove"
            :on-success="handlePaySuccess"
            multiple
            drag
            accept=".jpg,.png,.jpeg,.xlsx,.xls"
            :file-list="payFileList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入jpg/png/pdf格式文件。</span>
            </div>
          </el-upload>
        </el-form-item>

        <h1>商品信息</h1>
        <el-table :data="contractProductTable" @selection-change="handleContractSelectionChange">
          <el-table-column align="center" type="selection" width="50" :selectable="handelIsSelect"/>
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="商品编码">
                      <span>{{ props.row.productCode }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="商品类型">
                      <span>{{ props.row.productTypeName }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="计数单位">
                      <span>{{ props.row.unitName }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="尺寸单位">
                      <span>{{ props.row.ccUnitName }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="尺寸">
                      <span v-if="props.row.longWith || props.row.weight || props.row.height">{{ props.row.longWith + '*' + props.row.weight + '*' + props.row.height }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="重量">
                      <span>{{ props.row.zl }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="交货期（厂家）">
                      <span>{{ props.row.manufacturerDelivery }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="交货期（买家）">
                      <span>{{ props.row.delivery }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="详情">
                  <span>{{ props.row.detail }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
          <el-table-column label="商品型号" align="center" prop="modal" :show-overflow-tooltip="true"/>
          <el-table-column label="生产厂家" align="center" prop="scPurchaseCompanyName" :show-overflow-tooltip="true"/>
          <el-table-column label="商品数量" align="center" prop="productNum"/>
          <el-table-column label="成本" align="center" prop="oldOnlyPrice"/>
          <el-table-column label="单价" align="center" prop="onlyPrice"/>
          <el-table-column label="总价" align="center" prop="allPrice"/>
          <el-table-column label="状态" align="center" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_order_product_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBeforeForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 合同详情对话框 -->
    <el-dialog title="合同详情" :visible.sync="openLook" width="80%" append-to-body>
      <el-form>
        <el-form-item label="合同号" >
          {{orderCode}}
        </el-form-item>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="合同金额">
              {{contractInfo.contractPrice}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内容数量">
              {{contractInfo.productNum}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="厂家交货期">
              {{contractInfo.cjJhValid}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报价交货期">
              {{contractInfo.jhValid}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="付款方式">
          <dict-tag :options="dict.type.wms_pay_type" :value="contractInfo.payType"/>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="是否物流">
              <dict-tag :options="dict.type.sys_yes_no" :value="contractInfo.ifLogistics"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="contractInfo.ifLogistics === 'Y'">
            <el-form-item label="物流方式">
              <dict-tag :options="dict.type.wms_logistics" :value="contractInfo.logisticsModule"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" v-if="contractInfo.payType === '1'">
          <el-col :span="12">
            <el-form-item label="先款比例">
              {{contractInfo.prefixPayRate}} 备注：{{contractInfo.prefixRemark}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进度款比例">
              {{contractInfo.processPayRate}} 备注：{{contractInfo.processRemark}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" v-if="contractInfo.payType === '1'">
          <el-col :span="12">
            <el-form-item label="尾款比例">
              {{contractInfo.tailPayRate}} 备注：{{contractInfo.tailRemark}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="尾款支付时间">
              货到后{{contractInfo.tailPayTime}}天付款
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="支付金额">
              {{contractInfo.payPrice}}
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="合同附件" v-if="fileList.length > 0">
          <el-upload
            action=""
            class="upload-demo"
            :disabled="true"
            :on-preview="handlePreview"
            :file-list="fileList">
          </el-upload>
        </el-form-item>

        <el-form-item label="支付附件" v-if="payFileList.length > 0">
          <el-upload
            action=""
            class="upload-demo"
            :disabled="true"
            :on-preview="handlePreview"
            :file-list="payFileList">
          </el-upload>
        </el-form-item>
      </el-form>
      <h1>商品信息</h1>
      <el-table :data="orderProductTable">
        <el-table-column label="序号" align="center" type="index" width="50"/>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="商品编码">
                    <span>{{ props.row.productCode }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商品类型">
                    <span>{{ props.row.productTypeName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="计数单位">
                    <span>{{ props.row.unitName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="尺寸单位">
                    <span>{{ props.row.ccUnitName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="尺寸">
                    <span v-if="props.row.longWith || props.row.weight || props.row.height">{{ props.row.longWith + '*' + props.row.weight + '*' + props.row.height }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="重量">
                    <span>{{ props.row.zl }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="交货期（买家）">
                    <span>{{ props.row.delivery }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="详情">
                <span>{{ props.row.detail }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
        <el-table-column label="商品型号" align="center" prop="modal" :show-overflow-tooltip="true"/>
        <el-table-column label="生产厂家" align="center" prop="scPurchaseCompanyName"/>
        <el-table-column label="商品数量" align="center" prop="productNum"/>
        <el-table-column label="成本" align="center" prop="oldOnlyPrice"/>
        <el-table-column label="单价" align="center" prop="onlyPrice"/>
        <el-table-column label="总价" align="center" prop="allPrice"/>
        <el-table-column label="状态" align="center" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.wms_order_product_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 设置交货期 -->
    <el-dialog title="商品设置交货期" :visible.sync="openSettingDelivery" width="80%" append-to-body>
      <el-table :data="selectedProduct">
        <el-table-column label="序号" align="center" type="index" width="50"/>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="商品类型">
                    <span>{{ props.row.productTypeName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计数单位">
                    <span>{{ props.row.unitName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="商品数量">
                    <span>{{ props.row.productNum }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生产厂家">
                    <span>{{ props.row.scPurchaseCompanyName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="单价">
                    <span>{{ props.row.onlyPrice }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="总价">
                    <span>{{ props.row.allPrice }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="尺寸单位">
                    <span>{{ props.row.ccUnitName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="长度">
                    <span>{{ props.row.longWith }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="宽度">
                    <span>{{ props.row.weight }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="高度">
                    <span>{{ props.row.height }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="详情">
                <span>{{ props.row.detail }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="商品编码" align="center" prop="productCode" :show-overflow-tooltip="true"/>
        <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
        <el-table-column label="成本" align="center" prop="oldOnlyPrice"/>
        <el-table-column label="交货期" align="center">
          <template slot-scope="scope">
            <el-date-picker clearable
              v-model="scope.row.manufacturerDelivery"
              type="date"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
              placeholder="选择交货期" style="width: 100%">
            </el-date-picker>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-loading="btnLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContractOrder, getContractOrder, purchaseContractOrder, getContractOrders } from "@/api/wms/contractOrder";
import {getToken} from "@/utils/auth";

export default {
  name: "ContractOrder",
  dicts: ['wms_logistics','sys_yes_no','wms_contract_status','wms_pay_type','wms_order_product_status','wms_pay_type'],
  data() {
    let checkPayRate =(rule, value, callback) =>{
      let curRate = parseFloat(this.formContract.prefixPayRate) + parseFloat(this.formContract.processPayRate)
        + parseFloat(this.formContract.tailPayRate)
        if (curRate > 1) {
          return callback(new Error('先款进度款尾款总额不能大于1'));
        } else {
          callback()
        }
    }
    return {
      checkPayRate: checkPayRate,
      prefix: process.env.VUE_APP_BASE_API,
      orderCode: null,
      //按钮加载
      btnLoading: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同管理表格数据
      contractOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情弹出层
      openLook: false,
      // 设置商品交货期弹出层
      openSettingDelivery: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        offerCode: null,
        inquireCode: null,
        ifLogistics: null,
        logisticsModule: null,
        type: null,
        payType: null,
        status: null
      },
      // 附件参数
      uploadAccessory: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/wms/purchaseOrder/uploadPic"
      },
      // 订单商品列表
      orderProductTable: [],
      // 合同商品列表
      contractProductTable: [],
      //附件列表
      fileList: [],
      //支付附件列表
      payFileList: [],
      //附件列表
      accessoryList: [],
      //支付附件列表
      payAccessoryList: [],
      formContract: {},
      // 采购表单校验
      rulesContract: {
        payPrice: [
          { required: true, message: "支付金额不可为空", trigger: "blur" },
          { pattern: /^(0|[1-9])\d{0,8}(\.\d{1,2})?$/, message: '支付金额只能是数值最大9位整数2位小数', trigger: 'blur' }
        ],
        prefixPayRate: [
          { required: true, message: "先款不可为空", trigger: "blur" },
          { pattern: /^(1|(0(\.\d)?))$/, message: '先款比例只能是数值最大为1或小于1的1位小数', trigger: 'blur' },
          { required: true,validator:checkPayRate, trigger: 'blur' }
        ],
        processPayRate: [
          { required: true, message: "进度款不可为空", trigger: "blur" },
          { pattern: /^(1|(0(\.\d)?))$/, message: '进度款比例只能是数值最大为1或小于1的1位小数', trigger: 'blur' },
          { required: true,validator:checkPayRate, trigger: 'blur' }
        ],
        tailPayRate: [
          { required: true, message: "尾款不可为空", trigger: "blur"},
          { pattern: /^(1|(0(\.\d)?))$/, message: '尾款比例只能是数值最大为1或小于1的1位小数', trigger: 'blur' },
          { required: true,validator:checkPayRate, trigger: 'blur'}
        ],
        tailPayTime: [
          { required: true, message: "尾款支付时间不可为空", trigger: "blur" },
          { pattern: /^([0|[1-9]{1,3})$/, message: '尾款支付时间只能是整数最大999', trigger: 'blur' }
        ]
      },
      multiple: true,
      ids: [],
      contractRequireMap: new Map(),
      contractCodes: [],
      inquireCodes: [],
      //生产厂家
      scCj: [],
      //选择商品
      selectedProduct:[],
      pickerOptions: {
        disabledDate(time) {
          //时间选择框必须大于今天
          return time.getTime() < Date.now() - 8.64e7;
          // 或者 return time.getTime() < Date.now();
        }
      },
      contractInfo: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询合同管理列表 */
    getList() {
      this.loading = true;
      listContractOrder(this.queryParams).then(response => {
        this.contractOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSettingDelivery = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.scCj = []
      this.contractCodes = []
      this.inquireCodes = []
      this.contractProductTable = []
      this.fileList = []
      this.payFileList = []
      this.accessoryList = []
      this.payAccessoryList=[]
      this.selectedProduct = []
      this.formContract = {
        inquireCode: null,
        contractCode: null,
        productNum: 0,
        purchasePrice: 0,
        accessoryId: 0,
        payType: '1',
        rate: null,
        cgRate: null,
        wlRate: null,
        prefixPayRate: 0,
        processPayRate: 0,
        tailPayRate: 0,
        tailPayTime: 0,
        payPrice: 0,
      };
      this.resetForm("formContract");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 采购按钮操作 */
    handlePurchase() {
      this.reset();
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      getContractOrders(this.ids).then(response => {
        let data = response.data;
        this.formContract.offerCode = this.ids.join(',')
        this.contractProductTable = data.products
        this.open = true;
        this.title = "采购商品";
        loading.close();
      });
    },
    /** 提交前置按钮 */
    submitBeforeForm() {
      this.$refs["formContract"].validate(valid => {
        if (valid) {
          if (this.selectedProduct.length > 0) {
            if (this.accessoryList.length > 0) {
              if (this.payAccessoryList.length > 0 || (this.formContract.prefixPayRate == 0 && this.formContract.payType === '1')) {
                if (this.formContract.payType === '0') {
                  this.formContract.prefixPayRate = 1
                }
                let curRate = parseFloat(this.formContract.prefixPayRate) + parseFloat(this.formContract.processPayRate)
                + parseFloat(this.formContract.tailPayRate);
                if (curRate == 1) {
                  this.formContract.accessoryList = this.accessoryList
                  this.formContract.payAccessoryList = this.payAccessoryList
                  this.formContract.inquireCode = this.inquireCodes.join(',');
                  this.formContract.contractCode = this.contractCodes.join(',');
                  this.openSettingDelivery = true
                } else {
                  this.$message.error("先款、进度款、尾款总额必须等于1！")
                }
              } else {
                this.$message.error("请上传支付附件！")
              }
            } else {
              this.$message.error("请上传合同附件！")
            }
          } else {
            this.$message.error("请选择合同商品！")
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      let msg = ''
      for (let i = 0; i < this.selectedProduct.length; i++) {
        let item = this.selectedProduct[i];
        if (!item.manufacturerDelivery) {
          msg += "第" + (i+1) +"行格式异常，交货期不能为空；"
        }
      }

      if (msg) {
        this.$message.error(msg)
      } else {
        this.btnLoading = true
        this.formContract.products = this.selectedProduct
        purchaseContractOrder(this.formContract).then(response => {
          this.$modal.msgSuccess("采购成功");
          this.open = false;
          this.openSettingDelivery = false
          this.getList();
        }).finally(f => {
          this.btnLoading = false
        });
      }
    },
    // 文件点击事件
    handlePreview(file){
      window.open(file.url,'_blank');
    },
    // 查看合同商品
    handleLook(row){
      this.fileList = []
      this.payFileList = []
      const orderCode = row.orderCode
      this.orderCode = orderCode
      getContractOrder(orderCode).then(response => {
        let data = response.data;
        this.contractInfo = data
        this.orderProductTable = data.products
        let accessoryList = data.accessoryList
        let payAccessoryList = data.payAccessoryList

        if (accessoryList && accessoryList.length > 0) {
          accessoryList.forEach(item => {
            let urls = item.split("/")
            this.fileList.push({name: urls[urls.length - 1], url: this.prefix + item})
          })
        }
        if (payAccessoryList && payAccessoryList.length > 0) {
          payAccessoryList.forEach(item => {
            let urls = item.split("/")
            this.payFileList.push({name: urls[urls.length - 1], url: this.prefix + item})
          })
        }

        this.openLook = true
      });
    },
    // 附件删除
    handleRemove(file, fileList) {
      this.accessoryList.splice(this.accessoryList.indexOf(file.url), 1);
    },
    // 附件上传成功处理
    handlePiceSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.accessoryList.push(response.imgUrl)
      }
    },
    handlePayRemove(file, fileList) {
      this.payAccessoryList.splice(this.payAccessoryList.indexOf(file.url), 1);
    },
    // 附件上传成功处理
    handlePaySuccess(response, file, fileList) {
      if (response.code == 200) {
        this.payAccessoryList.push(response.imgUrl)
      }
    },
    // 支付类型变更事件
    handlePayTypeChange(val) {
      if (val === '1') {
        this.rulesContract.prefixPayRate = [
          { required: true, message: "先款不可为空", trigger: "blur" },
          { pattern: /^(1|(0(\.\d)?))$/, message: '先款比例只能是数值最大为1或小于1的1位小数', trigger: 'blur' },
          { required: true,validator:this.checkPayRate, trigger: 'blur' }
        ]
        this.rulesContract.processPayRate = [
          { required: true, message: "进度款不可为空", trigger: "blur" },
          { pattern: /^(1|(0(\.\d)?))$/, message: '进度款比例只能是数值最大为1或小于1的1位小数', trigger: 'blur' },
          { required: true,validator:this.checkPayRate, trigger: 'blur' }
        ]
        this.rulesContract.tailPayRate = [
          { required: true, message: "尾款不可为空", trigger: "blur" },
          { pattern: /^(1|(0(\.\d)?))$/, message: '尾款比例只能是数值最大为1或小于1的1位小数', trigger: 'blur' },
          { required: true,validator:this.checkPayRate, trigger: 'blur' }
        ]
        this.rulesContract.tailPayTime = [
          { required: true, message: "尾款支付时间不可为空", trigger: "blur" },
          { pattern: /^([0|[1-9]{1,3})$/, message: '尾款支付时间只能是整数最大999', trigger: 'blur' }
        ]
      } else {
        this.rulesContract.prefixPayRate = []
        this.rulesContract.processPayRate = []
        this.rulesContract.tailPayRate = []
        this.rulesContract.tailPayTime = []
      }
    },
    // 选择商品
    handleContractSelectionChange(selection) {
      this.selectedProduct = selection
      this.formContract.productNum = selection.length
      let contract = []
      let inquire = []
      let cj = []
      let purchase = 0
      selection.forEach(item => {
        if (contract.indexOf(item.orderCode) === -1){
          contract.push(item.orderCode)
        }
        if (inquire.indexOf(item.inquireCode) === -1){
          inquire.push(item.inquireCode)
        }
        if (cj.indexOf(item.scPurchaseCompany) === -1){
          cj.push(item.scPurchaseCompany)
        }
        purchase += parseFloat(item.oldOnlyPrice) * parseFloat(item.productNum)
      })
      this.formContract.purchasePrice = purchase.toFixed(2)
      this.contractCodes = contract
      this.inquireCodes = inquire
      this.scCj = cj
    },
    // 是否可以选择
    handelIsSelect(row, index){
      return row.status === '0' && this.scCj.includes(row.scPurchaseCompany) > -1
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.contractRequireMap = new Map()
      let ids = []
      selection.forEach(item => {
        ids.push(item.orderCode)
        this.contractRequireMap.set(item.orderCode, item.inquireCode)
      })
      this.ids = selection.map(item => item.orderCode)
      this.multiple = selection.length === 0
    },
    // 是否可以选择
    handelTableIsSelect(row, index){
      return row.status === '0'
    },
  }
};
</script>
